package com.data.modules.online.cgreport.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.PermissionData;
import com.data.common.exception.BootException;
import com.data.common.system.api.ISysBaseAPI;
import com.data.common.system.vo.DictModel;
import com.data.common.system.vo.DynamicDataSourceModel;
import com.data.common.util.BrowserUtils;
import com.data.common.util.ConvertUtils;
import com.data.modules.online.cgreport.entity.OnlCgreportHead;
import com.data.modules.online.cgreport.entity.OnlCgreportItem;
import com.data.modules.online.cgreport.entity.OnlCgreportParam;
import com.data.modules.online.cgreport.mapper.OnlCgreportHeadMapper;
import com.data.modules.online.cgreport.service.IOnlCgreportHeadService;
import com.data.modules.online.cgreport.service.IOnlCgreportItemService;
import com.data.modules.online.cgreport.service.IOnlCgreportParamService;
import com.data.modules.online.cgreport.service.impl.OnlCgreportAPIService;
import com.data.modules.online.cgreport.util.CgReportSqlUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Date 2022/1/26 14:10
 * @Author funing
 */
@SuppressWarnings("ALL")
@Slf4j
@RestController("onlCgreportAPI")
@RequestMapping({"/online/cgreport/api"})
public class OnlCgreportApiController {
    private static final Logger a = LoggerFactory.getLogger(OnlCgreportApiController.class);
    @Autowired
    private OnlCgreportAPIService cgreportAPIService;
    @Autowired
    private IOnlCgreportHeadService onlCgreportHeadService;
    @Autowired
    private IOnlCgreportItemService onlCgreportItemService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IOnlCgreportParamService onlCgreportParamService;

    @GetMapping({"/getColumnsAndData/{code}"})
    @PermissionData
    public Result<?> a(@PathVariable("code") String code, HttpServletRequest var2) {
        OnlCgreportHead var3 = (OnlCgreportHead)this.onlCgreportHeadService.getById(code);
        if (var3 == null) {
            return Result.error("实体不存在");
        } else {
            Result var4 = this.getData(code, var2);
            if (!var4.getCode().equals(200)) {
                return var4;
            } else {
                JSONObject var5 = JSON.parseObject(JSONObject.toJSONString(var4.getResult()));
                JSONArray var6 = var5.getJSONArray("records");
                Map var7 = this.onlCgreportHeadService.queryColumnInfo(code, false);
                JSONArray var8 = (JSONArray)var7.get("columns");
                HashMap var9 = new HashMap();
                if (var8 != null) {
                    for(int var10 = 0; var10 < var8.size(); ++var10) {
                        JSONObject var11 = var8.getJSONObject(var10);
                        Object var12 = var11.get("dictCode");
                        if (var12 != null) {
                            String var13 = var12.toString();
                            String var14 = var8.getJSONObject(var10).getString("dataIndex");
                            List var15 = this.onlCgreportHeadService.queryColumnDict(var13, var6, var14);
                            if (var15 != null) {
                                var9.put(var14, var15);
                                var11.put("customRender", var14);
                            }
                        }
                    }
                }

                var7.put("cgreportHeadName", var3.getName());
                var7.put("data", var4.getResult());
                var7.put("dictOptions", var9);
                return Result.ok(var7);
            }
        }
    }

    /** @deprecated */
    @Deprecated
    @GetMapping({"/getColumns/{code}"})
    public Result<?> getColumns(@PathVariable("code") String code) {
        OnlCgreportHead var2 = (OnlCgreportHead)this.onlCgreportHeadService.getById(code);
        if (var2 == null) {
            return Result.error("实体不存在");
        } else {
            QueryWrapper var3 = new QueryWrapper();
            var3.eq("cgrhead_id", code);
            var3.eq("is_show", 1);
            var3.orderByAsc("order_num");
            List var4 = this.onlCgreportItemService.list(var3);
            ArrayList var5 = new ArrayList();
            HashMap var6 = new HashMap();
            Iterator var7 = var4.iterator();

            while(var7.hasNext()) {
                OnlCgreportItem var8 = (OnlCgreportItem)var7.next();
                HashMap var9 = new HashMap(3);
                var9.put("title", var8.getFieldTxt());
                var9.put("dataIndex", var8.getFieldName());
                var9.put("align", "center");
                var9.put("sorter", "true");
                var5.add(var9);
                String var10 = var8.getDictCode();
                if (ConvertUtils.isNotEmpty(var10)) {
                    List var11 = null;
                    if (var10.toLowerCase().indexOf("select ") == 0) {
                        List var12 = ((OnlCgreportHeadMapper)this.onlCgreportHeadService.getBaseMapper()).executeSelete(var10);
                        if (var12 != null && var12.size() != 0) {
                            String var13 = JSON.toJSONString(var12);
                            var11 = JSON.parseArray(var13, DictModel.class);
                        }
                    } else {
                        var11 = this.sysBaseAPI.queryDictItemsByCode(var10);
                    }

                    if (var11 != null) {
                        var6.put(var8.getFieldName(), var11);
                        var9.put("customRender", var8.getFieldName());
                    }
                }
            }

            HashMap var14 = new HashMap(1);
            var14.put("columns", var5);
            var14.put("dictOptions", var6);
            var14.put("cgreportHeadName", var2.getName());
            return Result.ok(var14);
        }
    }

    @GetMapping({"/getData/{code}"})
    @PermissionData
    public Result<?> getData(@PathVariable("code") String code, HttpServletRequest var2) {
        log.info("==getData={}",code);
        Map var3 = CgReportSqlUtil.analysisRequestParam(var2);
        var3.put("getAll", var2.getAttribute("getAll"));

        try {
            return Result.OK(this.cgreportAPIService.getDataById(code, var3));
        } catch (BootException e) {
            log.error(e.getMessage(),e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping({"/getDataOrderByValue/{code}"})
    @PermissionData
    public Result<?> c(@PathVariable("code") String var1, HttpServletRequest var2) {
        OnlCgreportHead var3 = (OnlCgreportHead)this.onlCgreportHeadService.getById(var1);
        if (var3 == null) {
            return Result.error("实体不存在");
        } else {
            String var4 = var3.getCgrSql().trim();
            String var5 = var3.getDbSource();

            try {
                Map var6 = CgReportSqlUtil.analysisRequestParam(var2);
                Object var7 = var6.get("order_field");
                Object var8 = var6.get("order_value");
                if (!ConvertUtils.isEmpty(var7) && !ConvertUtils.isEmpty(var8)) {
                    String var9 = "force_" + var7;
                    var6.put(var9, var8);
                    var6.put("getAll", true);
                    Map var10 = this.cgreportAPIService.executeSelectSqlRoute(var5, var4, var6, var3.getId());
                    JSONArray var11 = JSON.parseArray(JSON.toJSONString(var10.get("records")));
                    var6.remove(var7.toString());
                    var6.remove(var9);
                    var6.remove("order_field");
                    var6.remove("order_value");
                    var6.put("getAll", var2.getAttribute("getAll"));
                    Map var12 = this.cgreportAPIService.executeSelectSqlRoute(var5, var4, var6, var3.getId());
                    JSONArray var13 = JSON.parseArray(JSON.toJSONString(var12.get("records")));
                    this.a(var11, var13);
                    var12.put("records", var13);
                    return Result.ok(var12);
                } else {
                    return Result.error("order_field 和 order_value 参数不能为空！");
                }
            } catch (Exception var14) {
                a.error(var14.getMessage(), var14);
                return Result.error("SQL执行失败：" + var14.getMessage());
            }
        }
    }

    private void a(JSONArray var1, JSONArray var2) {
        for(int var3 = 0; var3 < var1.size(); ++var3) {
            JSONObject var4 = var1.getJSONObject(var3);
            String var5 = var4.getString("id");
            int var6 = (int)var2.stream().filter((var1x) -> {
                return var5.equals(((JSONObject)var1x).getString("id"));
            }).count();
            if (var6 == 0) {
                var2.add(0, var4);
            }
        }

    }

    /** 报表 查询参数 列表
     * @param code
     * @return
     */
    @ApiOperation("报表 查询参数 列表")
    @GetMapping({"/getQueryInfo/{code}"})
    public Result<?> getQueryInfo(@PathVariable("code") String code) {
        try {
            List autoListQueryInfo = this.onlCgreportItemService.getAutoListQueryInfo(code);
            return Result.ok(autoListQueryInfo);
        } catch (Exception e) {
            a.info(e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    /** 报表参数 列表
     * @param code
     * @return
     */
    @ApiOperation("报表参数field 列表")
    @GetMapping({"/getParamsInfo/{code}"})
    public Result<?> getParamsInfo(@PathVariable("code") String code) {
        try {
            LambdaQueryWrapper<OnlCgreportParam> wrapper = new LambdaQueryWrapper();
            wrapper.eq(OnlCgreportParam::getCgrheadId, code);
            List list = this.onlCgreportParamService.list(wrapper);
            return Result.ok(list);
        } catch (Exception e) {
            a.info(e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    //TODO 为保证 匿名调用 暂时屏蔽
    //@PermissionData
    @RequestMapping({"/exportXls/{reportId}"})
    public void exportXls(@PathVariable("reportId") String reportId, HttpServletRequest request, HttpServletResponse response) {
        log.info("==exportXls=={}",reportId);
        String var4 = "报表";
        String var5 = "导出信息";
        if (!ConvertUtils.isNotEmpty(reportId)) {
            throw new BootException("参数错误");
        } else {
            Map map = null;

            try {
                map = this.onlCgreportHeadService.queryCgReportConfig(reportId);
            } catch (Exception e) {
                throw new BootException("动态报表配置不存在!");
            }

            List list = (List)map.get("items");
            request.setAttribute("getAll", true);
            Result result = this.getData(reportId, request);
            List list1 = null;
            if (result.getCode().equals(200)) {
                Map map1 = (Map)result.getResult();
                list1 = (List)map1.get("records");
            }

            ArrayList arrayList = new ArrayList();
            HashMap hashMap = new HashMap();
            HashMap hashMap1 = new HashMap();
            ArrayList arrayList1 = new ArrayList();

            String str;
            for(int i = 0; i < list.size(); ++i) {
                if ("1".equals(ConvertUtils.getString(((Map)list.get(i)).get("is_show")))) {
                    str = ((Map)list.get(i)).get("field_name").toString();
                    ExcelExportEntity fieldTxt = new ExcelExportEntity(((Map)list.get(i)).get("field_txt").toString(), str, 15);
                    Object dictCode = ((Map)list.get(i)).get("dict_code");
                    JSONArray var18 = JSONObject.parseArray(JSONObject.toJSONString(list1));
                    List dictModels = this.onlCgreportHeadService.queryColumnDict(ConvertUtils.getString(dictCode), var18, str);
                    if (dictModels != null && dictModels.size() > 0) {
                        ArrayList arrayList2 = new ArrayList();
                        Iterator iterator = dictModels.iterator();

                        while(iterator.hasNext()) {
                            DictModel dictModel = (DictModel)iterator.next();
                            arrayList2.add(dictModel.getText() + "_" + dictModel.getValue());
                        }

                        fieldTxt.setReplace((String[])arrayList2.toArray(new String[arrayList2.size()]));
                    }

                    Object replaceVal = ((Map)list.get(i)).get("replace_val");
                    if (ConvertUtils.isNotEmpty(replaceVal)) {
                        fieldTxt.setReplace(replaceVal.toString().split(","));
                    }

                    if (ConvertUtils.isNotEmpty(((Map)list.get(i)).get("group_title"))) {
                        String groupTitle = ((Map)list.get(i)).get("group_title").toString();
                        Object list2 = new ArrayList();
                        if (hashMap1.containsKey(groupTitle)) {
                            list2 = (List)hashMap1.get(groupTitle);
                            ((List)list2).add(str);
                        } else {
                            ExcelExportEntity var23 = new ExcelExportEntity(groupTitle, groupTitle, true);
                            arrayList1.add(var23);
                            ((List)list2).add(str);
                        }

                        hashMap1.put(groupTitle, list2);
                        fieldTxt.setColspan(true);
                    }

                    arrayList1.add(fieldTxt);
                }

                if ("1".equals(ConvertUtils.getString(((Map)list.get(i)).get("is_total")))) {
                    arrayList.add(((Map)list.get(i)).get("field_name").toString());
                }
            }

            Iterator iterator = hashMap1.entrySet().iterator();

            String var40;
            while(iterator.hasNext()) {
                Entry var38 = (Entry)iterator.next();
                var40 = (String)var38.getKey();
                List var42 = (List)var38.getValue();
                Iterator var45 = arrayList1.iterator();

                while(var45.hasNext()) {
                    ExcelExportEntity var47 = (ExcelExportEntity)var45.next();
                    if (var40.equals(var47.getName()) && var47.isColspan()) {
                        var47.setSubColumnList(var42);
                    }
                }
            }

            if (arrayList != null && arrayList.size() > 0) {
                iterator = arrayList.iterator();

                while(iterator.hasNext()) {
                    str = (String)iterator.next();
                    BigDecimal var41 = new BigDecimal(0.0D);
                    Iterator var43 = list1.iterator();

                    while(var43.hasNext()) {
                        Map var46 = (Map)var43.next();
                        String var48 = var46.get(str).toString();
                        if (var48.matches("\\d+(.\\d+)?")) {
                            BigDecimal var50 = new BigDecimal(var48);
                            var41 = var41.add(var50);
                        }
                    }

                    hashMap.put(str, var41);
                }

                list1.add(hashMap);
            }

            response.setContentType("application/vnd.ms-excel");
            ServletOutputStream var39 = null;

            try {
                str = BrowserUtils.checkBrowse(request);
                log.info("--str:{}",str);
                if (ObjectUtil.isNotEmpty(str) && str.length() >= "MSIE".length()
                        && "MSIE".equalsIgnoreCase(str.substring(0, 4))) {
                    response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(var4, "UTF-8") + ".xls");
                } else {
                    var40 = new String(var4.getBytes("UTF-8"), "ISO8859-1");
                    response.setHeader("content-disposition", "attachment;filename=" + var40 + ".xls");
                }

                Workbook var44 = ExcelExportUtil.exportExcel(new ExportParams((String)null, var5), arrayList1, list1);
                var39 = response.getOutputStream();
                var44.write(var39);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            } finally {
                try {
                    var39.flush();
                    var39.close();
                } catch (Exception e1) {
                    log.error(e1.getMessage(),e1);
                }

            }

        }
    }

    @GetMapping({"/getRpColumns/{code}"})
    public Result<?> d(@PathVariable("code") String var1) {
        LambdaQueryWrapper<OnlCgreportHead> var2 = new LambdaQueryWrapper();
        var2.eq(OnlCgreportHead::getCode, var1);
        OnlCgreportHead var3 = (OnlCgreportHead)this.onlCgreportHeadService.getOne(var2);
        if (var3 == null) {
            return Result.error("实体不存在");
        } else {
            Map var4 = this.onlCgreportHeadService.queryColumnInfo(var3.getId(), true);
            var4.put("cgRpConfigId", var3.getId());
            var4.put("cgRpConfigName", var3.getName());
            return Result.ok(var4);
        }
    }

    @PostMapping({"/testConnection"})
    public Result a(@RequestBody DynamicDataSourceModel var1) {
        Connection var2 = null;

        Result var4;
        try {
            Class.forName(var1.getDbDriver());
            var2 = DriverManager.getConnection(var1.getDbUrl(), var1.getDbUsername(), var1.getDbPassword());
            Result var3;
            if (var2 != null) {
                var3 = Result.ok("数据库连接成功");
                return var3;
            }

            var3 = Result.ok("数据库连接失败：错误未知");
            return var3;
        } catch (ClassNotFoundException var17) {
            a.error(var17.toString());
            var4 = Result.error("数据库连接失败：驱动类不存在");
            return var4;
        } catch (Exception var18) {
            a.error(var18.toString());
            var4 = Result.error("数据库连接失败：" + var18.getMessage());
        } finally {
            try {
                if (var2 != null && !var2.isClosed()) {
                    var2.close();
                }
            } catch (SQLException var16) {
                a.error(var16.toString());
            }

        }

        return var4;
    }

    @GetMapping({"/getReportDictList"})
    public Result<?> a(@RequestParam("sql") String var1, @RequestParam(name = "keyword",required = false) String var2) {
        List var3 = this.onlCgreportHeadService.queryDictSelectData(var1, var2);
        return Result.ok(var3);
    }
}
